import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as todoActions from '../store/actions/todo.actions'
import { getIn } from 'immutable'

class Main extends Component {

  componentDidMount() {
    // 调用具体的指令函数触发数据获取
    this.props.load_todo()
  }

  removeTodo(id) {
    if (window.confirm("确定删除么")) {
      console.log(id)
      this.props.remove_todo(id)
    }
  }

  handleChange = (id, e) => {
    this.props.motify_todo({ id: id, status: e.target.checked ? 1 : 0 })
  }

  modify_name = (id, ev) => {
    // modify_todo_name
    console.log(id, ev)
    // 切换状态
    this.props.modify_todo_edit({id, status: 0})
    // 修改数据
    this.props.modify_todo_name({id, taskName: ev.target.value})
  }

  render() {
    console.log(this.props, '======')
    return (
      <section className="main">
        <input className="toggle-all" type="checkbox" />
        <ul className="todo-list">
          {
            this.props.todos.map(item => {
              let classes = []
              if (item.isCompleted === 1) { classes.push('completed') }
              if (item.isEditing === 1) { classes.push('editing') }
              return (
                <li key={item.id} className= {classes.join(' ')} >
                <div className="view">
                  <input className="toggle" type="checkbox" 
                  onChange={this.handleChange.bind(this, item.id)}
                  defaultChecked={item.isCompleted === 1}/>
                  <label onDoubleClick={ () => {this.props.modify_todo_edit({id: item.id, status: 1})} }>{item.taskName}</label>
                  <button className="destroy" onClick={this.removeTodo.bind(this, item.id)}></button>
                </div>
                <input className="edit" onBlur={ this.modify_name.bind(this, item.id) } defaultValue={item.taskName}/>
              </li>
              )
            })
          }
        </ul>
      </section>
    );
  }
}

// 处理dispatch函数
const mapActionToProps = (dispatch) => {
  return {
    ...bindActionCreators(todoActions, dispatch)
  }
}

// 获取store中的数据
const mapStateToProps = (state) => {
  return {
    todos: filterTodos(getIn(state.todoReducer, ['todos']), getIn(state.todoReducer, ['filter']))
  }
}

// 定义过滤方法
function filterTodos(todos, filter) {
  switch (filter) {
    case 'all':
      return todos
    case 'Active':
      return todos.filter(todo => todo.isCompleted === 0)
    case 'Completed':
      return todos.filter(todo => todo.isCompleted === 1)
    default:
      return todos
  }
}

export default connect(mapStateToProps, mapActionToProps)(Main);
